"""
账号相关视图
"""
import traceback
import uuid
import logging

from django.contrib.auth import authenticate, login, logout
from django import forms
from django.contrib.auth.views import PasswordResetView
from django.core.cache import cache
from django.shortcuts import render, redirect

# Create your views here.
from rest_framework import permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core import mail
from django.core.mail import EmailMultiAlternatives
from django.template import Context, loader

from account.common import get_resource_list
from account.models import Account, Resource, Group
from account.serializers import ResourceSerializer
from common.permission_utils import CustomerPermission
from django.contrib.auth.hashers import make_password

from my_celery.tasks import send_sms, send_mail
from menu.utils import get_menu_list
from common.utils import get_qiniu_token
from goods.utils import create_order, create_sub_order

logger = logging.Logger('log')


class Register(APIView):
    """
    注册功能
    """

    def post(self, request):

        data = request.data
        username = data.get('username')
        password = data.get('password')
        phone = data.get('phone')
        if not Account.check_phone(phone):
            return Response({'code': 407, 'message': 'phone is exist'})
        try:
            account = Account.objects.create_user(username=username, password=password)
            account.phone = phone
            account.save()
            return Response({'code': 200, 'message': 'ok'})
        except:
            error = traceback.format_exc()
            print('2222222', error)
            return Response({'code': 500, 'message': error})


class Login(APIView):
    """
    登录功能
    """
    permission_classes = [permissions.AllowAny]

    def post(self, request):
        data = request.data
        send_sms.delay()
        username = data.get('username')
        password = data.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                resource_list = get_resource_list(user)
                superuser = str(user.is_superuser)
                return Response({'code': 200, 'data': {'resource_list': resource_list, 'superuser': superuser}})

            return Response({'code': 500, 'message': '用户已经被禁用'})
        # 否则就是用户名、密码有误
        return Response({'code': 406, 'message': '用户名或者密码错误'})


class LogOut(APIView):
    """
    退出登录
    """
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        print('0000000000000000000000')
        logout(request)
        return Response({'code': 200})


class GetUserResource(APIView):
    """
    获取用户资源列表
    """
    serializer_class = ResourceSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        try:
            user = request.user
            resource_list = get_resource_list(user)
            menu_list = get_menu_list(resource_list)
            return Response({'code': 200, 'data': menu_list})
        except:
            return Response({'code': 200, 'data': []})


class SendMail(APIView):
    """
    发送邮件
    """
    def post(self, request):
        subject = '测试邮件主题'
        context = {}
        from_email = '491061108@qq.com'  # 邮件发送人
        recipient_list = ['2837379503@qq.com', '18332782513@163.com']  # 邮件接收人

        email_template_name = 'template.html'
        t = loader.get_template(email_template_name)  # 导入模板

        html_content = t.render(context)  # 模板参数
        msg = EmailMultiAlternatives(subject, html_content, from_email, recipient_list)
        msg.attach_alternative(html_content, "text/html")
        msg.send()  # 发送邮件

        return Response({'code': 200, 'data': 'result'})


class ForgetPassword(APIView):
    """
    前端忘记密码，后端验证后发送邮件

    验证邮箱是否合法
    """
    def post(self, request):
        data = request.data
        email = data.get('email', '')
        if not email:
            return Response({'code': 405})
        account = Account.objects.filter(email=email).first()
        if not account:
            return Response({'code': 406})
        try:
            code = uuid.uuid1().hex
            cache.set(code, email, 60 * 60)
            subject = '测试邮件主题'
            url = 'http://127.0.0.1:8000/account/valid_email?code={}'.format(code)
            context = {'url': url}
            from_email = '491061108@qq.com'  # 邮件发送人
            recipient_list = ['2837379503@qq.com', '18332782513@163.com']  # 邮件接收人

            email_template_name = 'forgetpwd.html'
            t = loader.get_template(email_template_name)  # 导入模板

            html_content = t.render(context)  # 模板参数
            send_mail.delay(subject, html_content, from_email, recipient_list)
            return Response({'code': 200})
        except:
            error = traceback.format_exc()
            msg = '{} | params:{}'.format(error, locals())
            logger.error(msg)
            return Response({'code': 500, 'message': error})


class validEmail(APIView):
    """
    验证邮件
    """

    def get(self, request):
        data = request.query_params
        code = data.get('code')
        print('code', code)
        email = cache.get(code, '')
        print('2222222', email)
        if not email:
            return Response({'code': 400})
        url = 'http://127.0.0.1:8080/modify_password?code={}'.format(code)
        return redirect(url)


class GetQiniuToken(APIView):
    """
    获取七牛 token
    """
    def get(self, request):
        token = get_qiniu_token()
        return Response({'code': 200, 'data': token})


